Ext.ns('journal.home');

/**
 * Helper/Model class for the journal.home.Main class.
 */
journal.home.MainHandler = function() {
    // do NOT access DOM from here; elements don't exist yet
    // private variables
    // private functions

    var logger = journal.LoggerFactory.getLogger('journal.home.MainHandler');

    // public space
    return {

        /**
         * Will remove the node entry in the recent item in file menu. The additional separator will also be removed
         * when the count drops to zero. This method is primarily used when an Entry is deleted.
         */
        removeRecentFileItem : function(node) {
            var fileMenu = journal.home.Main.menubar.get(journal.Constant.Menu.FILE).menu;
            var oldItem = fileMenu.findById(node.id);

            journal.StateService.remove(journal.StateService.ST_RECENTLIST, node.getPath() + '|' + node.text);
            if (oldItem != null) {
                fileMenu.remove(oldItem);
                var recentListSize = journal.StateService.getCount(journal.StateService.ST_RECENTLIST);
                if (recentListSize == 0) {
                    var recentListSep = fileMenu.findById(journal.Constant.Menu.SEP_RECENT);
                    fileMenu.remove(recentListSep);
                }
            }
        },

        /**
         * Inserts a new recent item in the file menu. It will move the item on top when it is already existing. Will
         * also add the handler for the menu item.
         */
        addRecentFileItem : function(node) {
            var fileMenu = journal.home.Main.menubar.get(journal.Constant.Menu.FILE).menu;
            //var menuSize = fileMenu.items.length;
            var recentListSize = journal.StateService.getCount(journal.StateService.ST_RECENTLIST);
            var logoutSepIdx = fileMenu.items.indexOf(fileMenu.findById(journal.Constant.Menu.SEP_LOGOUT));

            var recentListSep;
            if ((recentListSep = fileMenu.findById(journal.Constant.Menu.SEP_RECENT)) == null) {
                fileMenu.insert(logoutSepIdx, recentListSep = new Ext.menu.Separator({
                    id : journal.Constant.Menu.SEP_RECENT
                }));
            }

            fileMenu.items.indexOf(recentListSep);
            var oldItem = fileMenu.findById(node.id);
            if (oldItem == null || fileMenu.items.indexOf(recentListSep) + 1 != fileMenu.items.indexOf(oldItem)) {
                // only when not yet already on top

                if (journal.StateService.contains(journal.StateService.ST_RECENTLIST, node.getPath() + '|' + node.text)) {
                    fileMenu.remove(oldItem);
                    journal.StateService.remove(journal.StateService.ST_RECENTLIST, node.getPath() + '|' + node.text);
                } else if (recentListSize == journal.Config.RecentFileListSize) {
                    fileMenu.remove(fileMenu.get(logoutSepIdx - 1));
                    recentListSize--;
                }

                journal.StateService.addFixed(journal.StateService.ST_RECENTLIST, node.getPath() + '|' + node.text,
                        journal.Config.RecentFileListSize);

                fileMenu.insert(fileMenu.items.indexOf(recentListSep) + 1, {
                    id : node.id,
                    node : node,
                    text : journal.Utility.limitString(node.text, journal.Config.RecentFileNameMaxSize),
                    iconCls : '',
                    handler : function() {
                        journal.home.Main.editorPanel.newTabHandler(node);
                    }
                });
                this.fixRecentItemIndex();
            }
        },

        /**
         * Will add the underlined number to the recent file list.
         */
        fixRecentItemIndex : function() {
            var fileMenu = journal.home.Main.menubar.get(journal.Constant.Menu.FILE).menu;
            var logoutSepIdx = fileMenu.items.indexOf(fileMenu.findById(journal.Constant.Menu.SEP_LOGOUT));
            var recentSepIdx = fileMenu.items.indexOf(fileMenu.findById(journal.Constant.Menu.SEP_RECENT));

            var recentListSize = journal.StateService.getCount(journal.StateService.ST_RECENTLIST);

            var computedRecentSize = logoutSepIdx - 1 - recentSepIdx;
            if (recentSepIdx == -1) {
            } else if (recentListSize != computedRecentSize) {
                logger
                        .error('Recent list size mismatched. Cookie: ' + recentListSize + ', Menu: '
                                + computedRecentSize);
                alert('Runtime Error: Mismatch in recent file list count.');
            } else {
                var spaceIdx;
                for ( var i = recentSepIdx + 1; i < logoutSepIdx; i++) {
                    var recentFileItem = fileMenu.get(i);
                    if (recentFileItem.text.indexOf('<u>') > -1) {
                        spaceIdx = recentFileItem.text.indexOf(' ');
                        recentFileItem.setText(recentFileItem.text.substring(spaceIdx + 1));
                    }
                    recentFileItem.setText('<u>' + (i - recentSepIdx) + '</u> ' + recentFileItem.text);
                }
            }
        },

        /**
         * Creates a recent item in the file menu. Used during startup to build recent list in menu from cookie. This is
         * used instead of addRecentFileItem when the TreeNode is not yet available.
         * 
         * @param scope - the journal.home.Main instance to reference the other major components from.
         * 
         * @public
         */
        createMenuItem : function(nodePath, nodeName, scope) {
            var fileMenu = scope.menubar.get(journal.Constant.Menu.FILE).menu;
            //var menuSize = fileMenu.items.length;
            var logoutSepIdx = fileMenu.items.indexOf(fileMenu.findById(journal.Constant.Menu.SEP_LOGOUT));

            var recentListSep = fileMenu.findById(journal.Constant.Menu.SEP_RECENT);
            if (!recentListSep) {
                fileMenu.insert(logoutSepIdx, new Ext.menu.Separator({
                    id : journal.Constant.Menu.SEP_RECENT
                }));
                recentListSep = fileMenu.findById(journal.Constant.Menu.SEP_RECENT);
            }
            fileMenu.insert(fileMenu.items.indexOf(recentListSep) + 1, {
                id : nodePath.substring(nodePath.lastIndexOf('/') + 1),
                node : nodePath,
                text : journal.Utility.limitString(nodeName, journal.Config.RecentFileNameMaxSize),
                iconCls : '',
                handler : function() {
                    journal.home.Main.editorPanel.newTabHandler(nodePath);
                }
            });
        },

        /**
         * This method handles global key intercept mechanism. This triggers when a key is pressed anywhere in the page.
         * 
         * @param e - the event object
         * @param scope - this should be the main object represented by this module. Usually the main returned object.
         */
        keyHandler : function(e, scope) {
            var key = String.fromCharCode(e.getKey()).toUpperCase().charCodeAt(0);

            if (scope.menubar.get(journal.Constant.Menu.FILE).hasVisibleMenu()) {
                scope.menubar.handlerKeypress(e, key);
            } else {

                if (e.ctrlKey && (key == e.W)) {// Ctr l + W
                    var actTab = scope.editorPanel.getActiveTab();
                    if (actTab != null) {
                        actTab.destroy();
                    }
                    e.stopEvent();
                } else if (e.ctrlKey && (e.getKey() == 115 || e.getKey() == e.S) && e.isSpecialKey()) {
                    var btnSave = scope.mainToolbar.get(journal.Constant.Button.SAVE);
                    if (!btnSave.disabled) {
                        btnSave.fireEvent('click');
                    }
                    e.stopEvent();
                } else if (e.altKey && key == e.F) {
                    scope.menubar.get(journal.Constant.Menu.FILE).showMenu();
                    e.stopEvent();
                }
            }
        }

    };
}(); // end of app

// end of file

